use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use web_sys::{window, MediaStreamConstraints, HtmlVideoElement, HtmlCanvasElement, MediaStream};

async fn capture_webcam(video: HtmlVideoElement, canvas: HtmlCanvasElement) -> Result<(), JsValue> {
    let mut constraints = MediaStreamConstraints::new();
    constraints.set_video(&true.into());

    let navigator = window().unwrap().navigator();
    let media = navigator.media_devices()?.get_user_media_with_constraints(&constraints)?;
    let stream = JsFuture::from(media).await?;

    // let video = HtmlVideoElement::new()?;
    let tracks = stream.dyn_ref::<MediaStream>().unwrap();
    video.set_src_object(Some(tracks));

    // Wait for video to be ready, then capture frame
    // let canvas = HtmlCanvasElement::new()?;
    canvas.set_width(video.video_width());
    canvas.set_height(video.video_height());

    let ctx = canvas
        .get_context("2d")?
        .unwrap()
        .dyn_into::<web_sys::CanvasRenderingContext2d>()?;

    ctx.draw_image_with_html_video_element(&video, 0.0, 0.0)?;
    let image_data = canvas.to_data_url()?; // Base64 encoded image

    Ok(())
}